// Definition for a binary tree node.
function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}

/**
 * @param {TreeNode} root
 * @return {number}
 */
var longestZigZag = function (root) {
  root = createTree(root);
  if(!root) return 0;
  let result = 0;
  function dfs(node, direction, depth) {
    result = Math.max(result, depth);
    if(!node) return ;
    if(direction == 'L') {
      if(node.left) dfs(node.left, 'R', depth + 1);
      if(node.right) dfs(node.right, 'L', 1);
    } else {
      if(node.right) dfs(node.right, 'L', depth + 1);
      if(node.left) dfs(node.left, 'R', 1);
    }
  }
  dfs(root, 'L', 0);
  dfs(root, 'R', 0);
  return result;
};
let root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1];
console.log(longestZigZag(root));
root = [1,1,1,null,1,null,null,1,1,null,1];
console.log(longestZigZag(root));
root = [1];
console.log(longestZigZag(root));

